<template>
  <auth-page>
    <view
      :class="['content', showCoupon ? 'disable-touch' : '']"
      :style="{ '--themeColor': themeColor }"
      @touchmove="move"
    >
      <nav-bar
        :title="!isFixed ? '' : shopInfo.shopName"
        :bgColor="!isFixed ? '#ffffff00' : '#fff'"
        :isPlaceholder="false"
        :supportWhiteBlack="!isFixed"
        ref="navBar"
      />
      <view class="head">
        <view class="head-bg">
          <xh-img :src="headImg[shopInfo.industry]" />
        </view>
        <view class="head-content">
          <view class="top">
            <view class="icon">
              <xh-img :src="shopInfo.logo" />
            </view>
            <view class="msg">
              <view
                class="title"
                @click="
                  handleMixinAuth($myTool.jumpPage, 'shopDetail', {
                    shopId: shopInfo.id,
                  })
                "
              >
                {{ shopInfo.shopName || "" }}
              </view>
              <view class="desc">
                <view
                  :class="['falg', shopInfo.allStatus == 1 ? '' : 'open']"
                  v-if="shopInfo.allStatus"
                >
                  {{ shopStatusOptions[shopInfo && shopInfo.allStatus] || "" }}
                </view>
                {{ industryType[shopInfo.industry] || "" }}｜月售{{
                  shopInfo.monthSales || 0
                }}
              </view>
            </view>
            <view
              class="btn"
              @click="handleMixinAuth(changeShop)"
              v-if="showChange"
              >切换门店</view
            >
          </view>
          <view class="bottom">
            <view
              class="btn"
              @click="
                handleMixinAuth($myTool.jumpPage, 'storeOrderList', {
                  shopId: shopInfo.id,
                })
              "
            >
              <view class="icon iconfont icon-dingdan"></view>
              <view class="title">订单</view>
            </view>
            <view
              class="btn"
              @click="
                handleMixinAuth(
                  $myTool.lookLocation,
                  shopInfo.latitude,
                  shopInfo.longitude,
                  shopInfo.shopName,
                  `${shopInfo.provinceCode}${shopInfo.cityCode}${shopInfo.areaCode}${shopInfo.address}`
                )
              "
            >
              <view class="icon iconfont icon-dingwei2"></view>
              <view class="title">导航到店</view>
            </view>
            <view v-if="isShowWiFi" class="btn" @click="handleToLink">
              <view class="icon iconfont">
                <u-icon :color="themeColor" name="wifi" size="56rpx" />
              </view>
              <view class="title">WIFI</view>
            </view>
            <button class="btn" open-type="share">
              <view
                class="icon iconfont icon-weixin"
                style="color: #05bd4e"
              ></view>
              <view class="title">分享</view>
            </button>
          </view>
        </view>
      </view>
      <view
        class="ticket"
        v-if="isShowCouponDown && couponList.length > 0 && couponList"
      >
        <scroll-view class="ticket_list" scroll-x="true">
          <view
            class="ticket_item"
            v-for="(item, index) in couponList"
            :key="index"
            @click="handleMixinAuth(pullDownCoupon, item, index)"
          >
            <view class="discount">
              {{
                item.denomination > 0
                  ? "¥" + item.denomination / 100
                  : item.discountPercent / 10 + "折"
              }}
            </view>
            <view class="rule">
              满{{ item.transactionMinimum / 100 }}元可用
              <view class="round_top"></view>
              <view class="round_bottom"></view>
            </view>
            <view :class="['get', item.pullDown ? 'took' : '']">
              {{ item.pullDown ? "已领" : "领" }}
            </view>
          </view>
        </scroll-view>
        <view class="see_all" @click="handleMixinAuth(showCouponList)">
          查看更多
        </view>
      </view>
      <view class="list list-placer" v-if="isFixed" style="height: 50px"></view>
      <view class="list">
        <view
          class="list-head"
          id="list-head"
          :class="[isFixed ? 'fixed' : '']"
          :style="{ top: navbarHeight + 'px' }"
        >
          <view class="right">
            <view
              v-for="(item, index) in tabList"
              :key="index"
              @click="handleMixinAuth(changeTab, index)"
            >
              <view :class="['text', index === tabActive ? 'active' : '']">
                <view>
                  {{ item }}
                </view>
              </view>
              <!--              <view-->
              <!--                :class="['text', index === tabActive ? 'active' : '']"-->
              <!--                v-else-->
              <!--              >-->
              <!--                {{ item }}-->
              <!--              </view>-->
            </view>
          </view>
          <view
            class="left"
            @click="
              handleMixinAuth($myTool.jumpPage, 'goodsSearch', {
                shopId: shopInfo.id,
              })
            "
            v-if="tabActive === 0"
          >
            <u-icon
              name="search"
              class="search"
              color="#88888860"
              size="26"
            />搜索
          </view>
        </view>
        <view
          class="list-content"
          :style="{ paddingBottom: `${68}px` }"
          v-if="tabActive === 0"
        >
          <list-empty
            v-if="datalist.length <= 0 || !datalist"
            :style="{ height: listHeight - 68 + 'px', width: '100%' }"
          />
          <view class="left" v-if="isFixed"></view>
          <view
            class="left"
            v-if="datalist.length > 0"
            :class="[isFixed ? 'fixed' : '']"
            :style="{ top: navbarHeight + 50 + 'px' }"
          >
            <scroll-view
              :scroll-y="isFixed"
              scroll-with-animation
              :style="{ height: `${listHeight - 68}px` }"
              :scroll-top="leftScrollTop"
            >
              <view
                @click="handleCategory(index)"
                :class="[
                  'text',
                  'nav-item',
                  currentIndex === index ? 'active' : '',
                ]"
                v-for="(item, index) in datalist"
                :id="'classify-' + item.id"
                :key="index"
              >
                <view class="text-content">
                  {{ item.name }}
                  <view
                    class="falg"
                    :class="[item.num >= 10 ? 'falgMax' : '']"
                    v-if="item.num > 0"
                    >{{ item.num }}</view
                  >
                </view>
              </view>
            </scroll-view>
          </view>
          <view class="right" v-if="datalist.length > 0">
            <!-- <scroll-view
              :scroll-y="(isFixed &&  lowCompatibility) || isScroll"
              :style="{ height: `${listHeight - 68}px` }"
              @scroll="scrollGoods"
              scroll-with-animation
              :scroll-into-view="contentId"
              class="shop-list"
              :bounces="false"
              :enhanced="true"
              :show-scrollbar="false"
            > -->
            <view
              class="class-ify"
              :id="'classify-' + item.id"
              v-for="(item, index) in datalist"
              :key="item.id"
              :style="{
                minHeight:
                  index + 1 == datalist.length
                    ? listHeight - 68 + 'px'
                    : 'auto',
              }"
            >
              <view class="classify-title">{{ item.name }}</view>
              <view v-for="child in item.goods" :key="child.id">
                <commodity :good="child" />
              </view>
              <view v-if="index + 1 == datalist.length" class="no_more"
                >没有更多了</view
              >
              <view
                style="height: 50px"
                v-if="index + 1 == datalist.length"
              ></view>
            </view>
            <!-- </scroll-view> -->
          </view>
        </view>
        <view :style="{ height: '100vh', width: '100%' }" v-if="tabActive == 1">
          <store-value ref="storeValue" />
        </view>
      </view>
      <shop-card v-show="tabActive == 0 && lowCompatibility" ref="shoping" />
      <shop-coupon
        :couponList="couponList"
        :visible.sync="showCoupon"
        @pullDownCoupon="pullDownCoupon"
      />
    </view>
    <view class="no_touch" @touchmove.stop.prevent v-if="showLoading">
      <view class="content">
        <view class="icon"><u-loading-icon></u-loading-icon></view>
        <view class="text">加载中...</view>
      </view>
    </view>
  </auth-page>
</template>

<script>
import commodity from "@/components/pageComponents/sp-store/commodity";
import shopCard from "@/components/pageComponents/sp-store/shopCard";
import storeValue from "@/pages/sp-store/pages/shop-index/components/storeValue";
import shopCoupon from "@/pages/sp-store/pages/shop-index/components/shopCoupon";
import ListEmpty from "@/components/baseComponents/list-enpty/index.vue";
import {
  getShopDetail,
  userJoinPubDomainBusinessUser,
  getShops,
  getQrcodeScan,
} from "@/service/api/sp-store/index";
import { getCategoryAndGoods } from "@/service/api/sp-store/commodity";
import {
  shopStatusObj,
  headImg,
  TABLE_QUERY_KEY,
  WIFI_STATE,
} from "../../const";
import { mixinAuth } from "@/mixin/sp-common/mixin-auth";
import { mapState } from "vuex";
import { receiveCoupon, getCoupon } from "@/service/api/sp-coupon/index";
import { getUrlQuery } from "@/utils/format";
import { appSetStorage } from "@/utils/storage";
import { isBindWifi ,getShopWifiListByPubShopId} from "@/service/api/sp-store/wifi";

export default {
  mixins: [mixinAuth],
  data() {
    return {
      tabActive: 0,
      upValue: 0,
      headHeight: 0,
      datalist: [],
      nodesTop: [],
      currentIndex: 0,
      contentId: "",
      listHeight: 0,
      isFixed: false,
      leftViewHeigt: 0,
      leftScrollTop: 0,
      isOpenTime: true,
      shopInfo: {},
      shopStatusOptions: shopStatusObj,
      pubShopId: "",
      pubDomainShopId: "",
      headImg: headImg,
      couponList: [],
      isShowCouponDown: true,
      showCoupon: false,
      navbarHeight: 0,
      showLoading: true,
      showChange: true,
      isTouch: true,
      isScroll: false,
      isShowWiFi: false,
      shopWiFiList: [],
      isTouch: true,
    };
  },
  computed: {
    ...mapState("sp-common/base", ["themeColor"]),
    ...mapState("sp-store/index", [
      "industryType",
      "cartData",
      "lowCompatibility",
    ]),
    ...mapState("sp-common/auth", ["app_token", "isAnonUser"]),
    tabList({ shopInfo }) {
      if (!shopInfo?.openBalanceConfig || shopInfo?.pubTag === 1) {
        return ["点餐"];
      }
      return ["点餐", "储值"];
    },
  },
  components: {
    commodity,
    shopCard,
    storeValue,
    ListEmpty,
    shopCoupon,
  },
  created() {},
  mounted() {
    const pages = getCurrentPages();
    this.pubShopId = this.$Route?.query?.shopId;
    this.tabActive = this.$Route?.query?.tabActive || 0;
    if (!this.app_token) return;
    this.initShop();
    this.innitWiFiConfig();
  },
  onShow() {
    uni.$on("updateData", (res) => {
      if (res.setPassWord) {
        this.$refs.storeValue.getBaseConfig();
      }
    });
    if (!this.app_token) return;
    this.$store.commit("sp-store/index/SET_DINE", "");
    this.innitQRCode();
  },
  watch: {
    app_token(value) {
      if (value) {
        this.initShop();
        this.innitWiFiConfig();
        this.innitQRCode();
      }
    },
    isAnonUser(value) {
      if (!value) {
        userJoinPubDomainBusinessUser({ pubDomainShopId: this.pubShopId });
        this.$store.dispatch("sp-store/index/initCart", this.pubShopId);
      }
    },
    cartData: {
      handler(val) {
        this.setFalgList();
      },
      deep: true,
    },
  },

  // 分享
  onShareAppMessage() {
    let {
      shopInfo: { shopName, logo, copywrite },
    } = this;
    return {
      title: copywrite ? copywrite : shopName,
      path: `pages/sp-store/pages/shop-index/index?shopId=${this.pubShopId}`,
      imageUrl: logo ? process.env.VUE_APP_BASE_FileUrl + logo : "",
      success: (res) => {
        console.info(res);
      },
    };
  },

  methods: {
    innitQRCode() {
      if (this.$Route?.query?.q) {
        //来自桌码
        const options = this.$Route?.query;
        //q=https%253A%252F%252Fcloudtest.xiangsaopay.com%252Fqr%253Ftype%253Dorder%2526deptId%253D1123598813738675201%2526code%253DFHB1230000000009&scancode_time=1679380269
        const q = decodeURIComponent(options?.q);
        const query = getUrlQuery(q);
        this.fetchQRCodeDetail(query);
      }
    },
    async fetchQRCodeDetail(query) {
      const res = await getQrcodeScan({ deviceNo: query.code });
      if (res) {
        this.pubDomainShopId = res?.bizData?.pubDomainShopId;
        this.pubShopId = res?.bizData?.pubDomainShopId;
        appSetStorage(TABLE_QUERY_KEY, JSON.stringify(res?.bizData));
        console.log("桌码参数", res?.bizData);
        this.$nextTick(() => {
          this.initShop();
        });
      }
    },
    async innitWiFiConfig() {
      if (!this.pubShopId) return;
      const res = await isBindWifi({ pubDomainShopId: this.pubShopId });
      this.isShowWiFi = !!res;
      this.fetchShopWiFiList();
    },

    fetchShopWiFiList() {
      getShopWifiListByPubShopId({
        pubDomainShopId: this.$Route.query.shopId,
      }).then((res) => {
        console.log("门店WiFi", res);
        if (!res) return;
        this.shopWiFiList = res;
      });
    },
    handleToLink() {
      if (this.shopWiFiList.length === 1) {
        const item = this.shopWiFiList[0];
        this.$Router.push({
          name: "linkWifi",
          params: {
            name: item.wifiName,
            password: item.password,
            deviceNo: item.wifiCode,
          },
        });
      } else {
        this.$Router.push({
          name: "wifiList",
          params: {
            shopId: this.$Route.query.shopId,
          },
        });
      }
    },
    innitQRCode() {
      if (this.$Route?.query?.q) {
        //来自桌码
        const options = this.$Route?.query;
        //q=https%253A%252F%252Fcloudtest.xiangsaopay.com%252Fqr%253Ftype%253Dorder%2526deptId%253D1123598813738675201%2526code%253DFHB1230000000009&scancode_time=1679380269
        const q = decodeURIComponent(options?.q);
        const query = getUrlQuery(q);
        this.fetchQRCodeDetail(query);
      }
    },
    async fetchQRCodeDetail(query) {
      if (this.pubDomainShopId && this.pubShopId) return;
      const res = await getQrcodeScan({ deviceNo: query.code });
      if (res) {
        this.pubDomainShopId = res?.bizData?.pubDomainShopId;
        this.pubShopId = res?.bizData?.pubDomainShopId;
        appSetStorage(TABLE_QUERY_KEY, JSON.stringify(res?.bizData));
        console.log("桌码参数", res?.bizData);
        this.$nextTick(() => {
          this.initShop();
          this.innitWiFiConfig();
        });
      }
    },
    async initShop() {
      let { pubShopId, isAnonUser, pubDomainShopId } = this;
      console.log("初始化商店信息", pubShopId);
      if (!pubShopId) {
        this.pubShopId = pubDomainShopId;
      }
      if (!pubShopId) return;
      await this.getData();
      await this.getShopDetail();
      if (!isAnonUser) {
        await this.$store.dispatch("sp-store/index/initCart", pubShopId);
        await userJoinPubDomainBusinessUser({ pubDomainShopId: pubShopId });
      }
      await this.setShowChange();
    },
    // 切换门店
    changeShop() {
      uni.navigateTo({
        url: `pages/sp-store/pages/public-shopSearch/index?shopId=${this.shopInfo.pubDomainBusinessId}`,
        events: {
          acceptDataFromOpenedPage: (data) => {
            this.pubShopId = data?.shopId;
            this.tabActive = 0;
            this.$store.commit("sp-store/index/SET_DINE", "");
            this.initShop();
          },
        },
      });
    },
    // 切换tab
    changeTab(key) {
      if (this.tabActive == key) return;
      this.tabActive = key;
      let { headHeight } = this;
      this.currentIndex = 0;
      uni.pageScrollTo({
        scrollTop: headHeight,
        duration: 500,
      });
    },
    // 获取门店详情
    async getShopDetail() {
      let { pubShopId: id, shopInfo } = this;
      if (Object.keys(shopInfo).length > 0) return;
      await getShopDetail({ id }).then((res) => {
        this.shopInfo = res;
        // this.$store.commit("sp-store/index/SET_DINE", datas[0]);
        this.$store.commit("sp-store/index/SET_SHOP_STATUS", res.allStatus);
        this.$store.commit("sp-store/index/SET_PUBSHOP_INFO", res);
        let { allStatus } = res;
        if (allStatus == 2 || allStatus == 1) {
          uni.showModal({
            content:
              allStatus == 1
                ? "当前门店已打烊，请重新选择门店下单"
                : "当前门店已关停，无法查看门店详情",
            showCancel: false,
            confirmText: "我知道了",
            success: (res) => {
              if (res.confirm) {
                this.$myTool.jumpPage("back");
              }
            },
          });
        }
      });
      let { pubDomainBusinessId, id: pubDomainShopId } = this.shopInfo;
      // 获取优惠券列表
      await getCoupon({
        pubDomainBusinessId,
        pubDomainShopId,
        pageSize: 999,
        pageNum: 1,
      }).then((res) => {
        let filter = JSON.parse(JSON.stringify(res));
        filter.length === 0 && (this.isShowCouponDown = false);
        filter.forEach((item) => {
          item.pullDown = false;
        });
        this.couponList = filter;
        this.$nextTick(() => {
          if (
            this.$Route?.query?.showTicket &&
            this.$Route?.query?.showTicket === "true"
          ) {
            this.showCouponList();
          }
        });
      });
    },
    // 获取所有商品及相关分类
    getData() {
      let { pubShopId } = this;
      if (this.datalist.length > 0) return;
      getCategoryAndGoods({ pubShopId }).then((res) => {
        this.datalist = res.categoryAndGoods;
        this.$nextTick(() => {
          this.setFalgList();
          this.setGoodsHeight();
        });
      });
    },
    // 分类点击
    handleCategory(index) {
      let { nodesTop, currentIndex } = this;
      if (currentIndex == index) return;
      this.currentIndex = index;
      this.isFixed = true;
      this.isTouch = false;
      uni.pageScrollTo({
        scrollTop: nodesTop[index],
        duration: 500,
        success: () => {
          setTimeout(() => {
            this.move();
          }, 1000);
        },
      });
    },
    // 设置商品分类数据高度
    setGoodsHeight() {
      let { isShowCouponDown, dataList, couponList } = this;
      const query = uni.createSelectorQuery().in(this);
      let pageHeight = 0;
      let navbarHeight = this.$refs.navBar.exportHeight() || 60;
      this.navbarHeight = navbarHeight;
      let cartHeight = this.$refs.shoping.exportHeight() || 68;
      let ticketHeight = 0;
      let safetyHeight = 0;
      if (dataList) {
        query
          .select(".nav-item,")
          .boundingClientRect((data) => {
            this.leftViewHeigt = data.height;
          })
          .exec();
      }
      uni.getSystemInfo({
        success: (res) => {
          let {
            safeAreaInsets: { bottom, top },
            windowHeight,
          } = res;
          pageHeight = windowHeight;
          safetyHeight = bottom;
        },
      });
      if (isShowCouponDown && couponList.length > 0) {
        query
          .selectAll(".ticket")
          .boundingClientRect((data) => {
            ticketHeight = isShowCouponDown ? data[0].height + 12 || 55 : 0;
          })
          .exec();
      }
      query
        .selectAll(".head,#list-head,")
        .boundingClientRect((data) => {
          this.headHeight = data[0].height + ticketHeight - navbarHeight;
          this.listHeight =
            pageHeight - navbarHeight - cartHeight + safetyHeight;
          // this.showLoading = false;
        })
        .exec();
      query
        .selectAll(".classify-title")
        .boundingClientRect((rects) => {
          let nodesTop = [];
          for (let item of rects) {
            nodesTop.push(
              parseInt(item.top - rects[0].top + this.headHeight + 7)
            );
          }
          this.nodesTop = nodesTop;
          this.showLoading = false;
        })
        .exec();
    },
    // 领取优惠券
    pullDownCoupon(item, index) {
      let { receiveCode } = item;
      let { couponList } = this;
      if (couponList[index].pullDown) return;
      receiveCoupon({
        receiveCode,
      })
        .then((res) => {
          console.log(res);
          this.couponList[index].pullDown = true;
          wx.showToast({
            title: "领取成功",
          });
        })
        .catch((res) => {
          wx.showToast({
            title: res,
            icon: "none",
          });
        });
    },
    // 查看更多优惠券
    showCouponList() {
      this.showCoupon = true;
    },
    // 设置类目的falg
    setFalgList() {
      let {
        cartData: { items },
        datalist,
      } = this;
      if (datalist == null) return;
      datalist.forEach((item) => {
        item.num = 0;
      });
      if (items == null) return;
      items.forEach((item) => {
        datalist.forEach((k) => {
          if (
            item.stockNum >= item.num &&
            item.errorCode !== 55101 &&
            item.errorCode !== 55102
          ) {
            if (item.categoryId == k.id) {
              k.num += item.num;
            }
          }
        });
      });
    },
    setShowChange() {
      let {
        shopInfo: { shopType, pubDomainBusinessId },
      } = this;
      let queryParams = {
        latitude: "",
        longitude: "",
        // 门店类型 1餐饮；2便利店；3休闲娱乐；4美容美发， 不传则查全部类型
        shopType,
        sortType: 1,
        pageNum: 1,
        pageSize: 10,
        pubDomainBusinessId,
      };

      this.$getUserLocation().then((res) => {
        let result = res?.currentLocation
          ? res?.currentLocation
          : res?.location;
        let { longitude, latitude } = result;
        queryParams = Object.assign({}, queryParams, {
          longitude,
          latitude,
        });
        getShops(queryParams).then((res) => {
          if (res?.list?.length < 2) {
            this.showChange = false;
          }
        });
      });
    },
    move() {
      this.isTouch = true;
    },
  },
  // 监听页面滚动距离
  onPageScroll(e) {
    this.isFixed = e.scrollTop >= this.headHeight ? true : false;
    let top = e.scrollTop;
    let { nodesTop, datalist, leftViewHeigt, isTouch } = this;
    if (isTouch) {
      for (let e = 0; e < nodesTop.length; e++) {
        if (top <= nodesTop[e + 1] && top >= nodesTop[e]) {
          if (this.currentIndex !== datalist[e].id) {
            this.currentIndex = e;
            this.leftScrollTop = leftViewHeigt * (datalist[e].id - 2);
          }
        } else if (top >= nodesTop[e] && !nodesTop[e + 1]) {
          this.currentIndex = e;
          this.leftScrollTop = leftViewHeigt * (datalist[e - 1].id - 2);
        }
      }
    }
  },
};
</script>
<style>
page {
  background: #f7f7f7;
  height: 100vh;
  width: 100%;
}
</style>
<style lang="scss" scoped>
@import "../../css/index";
</style>
